Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 5x 5x 5x 5x 5x 5x 5x 4x 7x 1x 1x 3x 3x 3x 7x 2x 2x 2x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 8x 8x 8x 8x 8x 9x 8x 8x 8x 8x 8x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | export const dynamic = "force-dynamic";
import { NextRequest, NextResponse } from 'next/server';
import {
withAdmin,
withErrorHandling,
successResponse,
ApiError,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { } from "next-auth";
import { Prisma } from "@prisma/client";
import { z } from "zod";
// ============================================================================
// VALIDATION SCHEMAS
// ============================================================================
const updateProductSchema = z.object({
title: z.string().min(1).optional(),
description: z.string().optional().nullable(),
price: z.number().positive().optional(),
discountedPrice: z.number().positive().optional().nullable(),
stock: z.number().int().nonnegative().optional(),
sku: z.string().optional().nullable(),
categoryId: z.number().int().positive().optional(),
specifications: z.record(z.string(), z.unknown()).optional().nullable(),
// Accept array of strings, a JSON string that parses to an array, or null
details: z.union([
z.array(z.string()),
z.string().transform((val, ctx) => {
try {
const parsed = JSON.parse(val);
if (Array.isArray(parsed)) {
return parsed as string[];
}
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Details must be an array of strings" });
return z.NEVER;
} catch {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Invalid JSON string for details" });
return z.NEVER;
}
}),
z.null(),
]).optional() });
// ============================================================================
// TYPES
// ============================================================================
interface ProductDetail {
id: number;
title: string;
description: string | null;
price: number;
discountedPrice: number;
stock: number;
sku: string | null;
categoryId: number;
category: Prisma.CategoryGetPayload<object>;
images: Prisma.ProductImageGetPayload<object>[];
specifications: Prisma.JsonValue;
details: Prisma.JsonValue;
rating: number;
reviewCount: number;
createdAt: Date;
updatedAt: Date;
}
// ============================================================================
// HANDLERS
// ============================================================================
/**
* GET /api/admin/products/[productId]
* Get product details
*/
async function handleGet(
request: NextRequest,
context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<ProductDetail> | ApiErrorResponse>> {
const resolvedParams = await context?.params;
const productId = parseInt(resolvedParams?.productId || "");
if (isNaN(productId)) {
throw ApiError.invalidId("productId");
}
const product = await prisma.product.findUnique({
where: { id: productId },
include: {
category: true,
images: true,
reviews: { select: { rating: true } } } });
if (!product) {
throw ApiError.notFound("Product", productId);
}
const avgRating =
product.reviews.length > 0
? Math.round(
(product.reviews.reduce((sum, r) => sum + r.rating, 0) / product.reviews.length) *
10
) / 10
: 0;
return successResponse({
...product,
rating: avgRating,
reviewCount: product.reviews.length });
}
/**
* Shared update handler for PATCH and PUT
*/
async function handleUpdate(
request: NextRequest,
context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<Prisma.ProductGetPayload<object>> | ApiErrorResponse>> {
const resolvedParams = await context?.params;
const productId = parseInt(resolvedParams?.productId || "");
if (isNaN(productId)) {
throw ApiError.invalidId("productId");
}
const body = await request.json();
// Validate request body
const validationResult = updateProductSchema.safeParse(body);
if (!validationResult.success) {
throw ApiError.validation(
"Invalid product data",
validationResult.error.issues
);
}
const { title, description, price, discountedPrice, stock, sku, categoryId, specifications, details } = validationResult.data;
const product = await prisma.product.update({
where: { id: productId },
data: {
...(title && { title }),
...(description !== undefined && { description }),
...(price && { price }),
...(discountedPrice && { discountedPrice }),
...(stock !== undefined && { stock }),
...(sku !== undefined && { sku }),
...(categoryId && { category: { connect: { id: categoryId } } }),
...(specifications !== undefined && { specifications: specifications as Prisma.InputJsonValue }),
...(details !== undefined && { details: JSON.stringify(details) }),
},
include: {
category: true,
images: true,
},
});
return successResponse(product);
}
/**
* DELETE /api/admin/products/[productId]
* Delete product
*/
async function handleDelete(
request: NextRequest,
context: RouteContext | undefined
): Promise<NextResponse<ApiSuccessResponse<{ message: string }> | ApiErrorResponse>> {
const resolvedParams = await context?.params;
const productId = parseInt(resolvedParams?.productId || "");
if (isNaN(productId)) {
throw ApiError.invalidId("productId");
}
await prisma.product.delete({
where: { id: productId } });
return successResponse({
message: "Product deleted successfully" });
}
// ============================================================================
// EXPORTS
// ============================================================================
export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handleUpdate));
export const PUT = withErrorHandling(withAdmin(handleUpdate));
export const DELETE = withErrorHandling(withAdmin(handleDelete));
|